
import zmq, logging
from uuid import uuid4

import tnetstrings
#import admincommands

def encode(path, method='GET', params={}, src=0, dst=0):
	"""return tnetstrings for this command

	UUID ID SIZE:PATH,SIZE:METHOD,SIZE:PARAMS}
	"""
	msg = '%s %s %s%s%s' % (
			src, dst, tnetstrings.dump(path), 
			tnetstrings.dump(method), 
			tnetstrings.dump(params))
		
	logging.debug("ReqRep.encode() msg : %s" % (msg))
	return msg
#encode()

def decode(netstr):
	"""
	docstring for decode
	UUID ID SIZE:PATH,SIZE:METHOD,SIZE:PARAMS]
	"""

	logging.debug("decode() netstr : %s" % (netstr,))
	parts = netstr.split(None, 2)

	resp = {'src': parts[0]}
	resp['dst'] = parts[1]
	netstr = parts[2]

	resp['path'], rest = tnetstrings.parse(netstr)
	resp['method'], rest = tnetstrings.parse(rest)
	params = {}
	if rest:
		resp['params'], _ = tnetstrings.parse(rest)

	return resp
#decode()


class ReqRep(object):
	"""docstring for ReqRep"""
	def __init__(self, transport, host=None, port=None, endpoint=None):

		logging.debug("ReqRep() transport:%s, host:%s, port:%s, endpoint:%s" % (
				transport, host, port, endpoint))

		self.log = logging.getLogger( "dmq_service" ).log
		
		self.transport = transport
		self.host = host
		self.port = port
		self.endpoint = endpoint
		self.socket = None
		self._ztype = zmq.REQ

		self.uuid = uuid4().hex

		if transport not in ['tcp','ipc']:
			raise Exception("ReqRep() Invalid transport, '%s'" % (transport,))

		if transport == 'ipc':
			self.device = 'ipc://%s' % (endpoint)
		elif transport == 'tcp':
			self.device = 'tcp://%s:%s' % (host, port)

		#self.log(logging.DEBUG, 'ReqRep() Connecting to device : %s' % (self.device,))
		logging.debug('ReqRep() Connecting to device : %s' % (self.device,))

		context = zmq.Context.instance()
		self.socket = context.socket(self._ztype)
		self.socket.connect(self.device)

	#__init__()


#ReqRep

class Req(ReqRep):
	"""docstring for Req

		UUID ID SIZE:PATH,SIZE:METHOD,SIZE:PARAMS}
	"""
	def __init__(self, transport, host=None, port=None, endpoint=None):
		self._ztype = zmq.REQ
		super(Req, self).__init__(transport, host=host, port=port, endpoint=endpoint)
	#__init__()

	def send(self, path, params, method='GET', 
		  src=0, dst=0):
		"""docstring for send"""
		logging.debug("Req.send( src:%s, dst:%s, path:%s, params:%s)" %
				(src, dst, path, params))

		msg = encode(path, method, params, src, dst)

		logging.debug("Req.send() sending : %s" %
				(msg,))

		self.socket.send(msg)
		resp = self.socket.recv()
		logging.debug("Req.send() Received : %s" % (resp,))
		self.socket.close()
		return resp
	#send()
#Req

class Rep(ReqRep):
	"""docstring for Rep"""
	def __init__(self, transport, host=None, port=None, endpoint=None):
		self._ztype = zmq.REP
		super(Rep, self).__init__(transport, host=host, port=port, endpoint=endpoint)
	#__init__()

	def recv(self):
		"""docstring for recv"""
		#decode()
		pass
	#recv()
#Rep
